<template>
  <el-breadcrumb
    class="breadcrumb-container"
    separator="/"
  >
    <el-breadcrumb-item
      v-for="(item, index) in breadcrumbs"
      :key="item.path"
    >
      <!-- 最后一个不可点击 -->
      <span
        v-if="index === breadcrumbs.length - 1"
        class="no-redirect"
      >
        {{ item.meta.title }}
      </span>
      <!-- 其他可点击跳转 -->
      <router-link
        v-else
        :to="item.redirect || item.path"
      >
        {{ item.meta.title }}
      </router-link>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script>
import { compile } from 'path-to-regexp'

export default {
  name: 'Breadcrumb',
  data () {
    return {
      breadcrumbData: [] // 原名为breadcrumbs，改为breadcrumbData避免冲突
    }
  },
  computed: {
    breadcrumbs () {
      return this.breadcrumbData // 指向data中的重命名变量
    }
  },
  watch: {
    $route () {
      this.getBreadcrumb()
    }
  },
  created () {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb () {
      // 过滤掉没有title的路由
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]

      // 如果不是首页，则自动添加首页路由
      if (first && first.name !== 'Dashboard') {
        matched = [{
          path: '/dashboard',
          meta: { title: '首页' }
        }].concat(matched)
      }

      this.breadcrumbData = matched.map(item => {
        // 处理动态路由参数（如/:id）
        const toPath = compile(item.path)(this.$route.params)
        return {
          path: toPath,
          meta: item.meta,
          redirect: item.redirect
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.breadcrumb-container {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 10px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }

  ::v-deep .el-breadcrumb__inner a,
  ::v-deep .el-breadcrumb__inner.is-link {
    font-weight: normal;
    color: #999;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}
</style>
